<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h1>the ajax 02 page</h1>
    <button onclick=doAjaxGet("get")>Do Ajax Get</button>
    <button onclick=doAjaxGet("post")>Do Ajax Post</button>
    <button onclick=doAjaxGet("put")>Do Ajax Put</button>
    <button onclick=doAjaxGet("delete")>Do Ajax Delete</button>
    <div id="result"></div>
</div>

<script>
    function doAjaxGet(req) {
        console.log(req)
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(xhr.readyState==4){
                if (xhr.status==200){
                    var result = xhr.responseText;
                    document.getElementById("result").innerHTML = result;
                }
            }
        }
        switch (req) {
            //获取
            case "get":
                xhr.open(req,"http://localhost:8080/doAjaxGet",true);
                xhr.send(null);//get请求send方法内部不传数据可以为null
                break;
            case "post":
                //当做一个添加操作，或者想服务端提交的数据比较多时可以考虑使用post请求
                xhr.open(req,"http://localhost:8080/doAjaxPost",true);
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
                xhr.send("id=200&name=xiaomi&remark=very good");//post请求数据要写到send方法
                break;
            case "put":
                xhr.open(req,"http://localhost:8080/doAjaxPut",true);
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
                xhr.send("id=200&name=hongmi&remark=very very good");//post请求数据要写到send方法
                break;
            case "delete":
                xhr.open(req,"http://localhost:8080/doAjaxDelete/200",true);
                xhr.send(null);
                break;

        }

    }
</script>
</body>
</html>